<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
* shopee 数据接口
*/
class Shopeedata 
{  
  //  protected $partner_id=12127;
	 // protected $key='8f4819490abe1caa67bb2207b19a8aebe67548e93339815e7775c15c78e6e462';

	function __construct()
	{    
		 $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
       $this->CI->load->library('Amazondata');
       $this->amazondata=new amazondata();
	}

  public function start(){
    $sql="select * from d_shop where `platfromname`='Shopee';";
    $arr_row = $this->db1->query($sql)->result_array();
     // var_export($arr_row);
    //判断是否为空
    if(!empty($arr_row)){
      foreach ($arr_row as $value) {
      	//var_export($value);
      	if (empty($value["amazonkey"])) {
      		continue;
      	}
        $amazonkey = json_decode($value["amazonkey"],true);
              //判断是否存在shopid
          if(isset($amazonkey['shopeetoken'])){
          //存在shopid执行orderlist
          $this->orderlist($amazonkey['shopeetoken'],$value['id']);
          $this->returnlist($amazonkey['shopeetoken'],$value['id']);
          // echo $this->shopeeapi('itemslist',$amazonkey['shopeetoken']);
          // exit;
         }
      }
    }
    return 'end';
  }


  //产品信息更新.由于使用不多，所以单独独立出来，由于数据量较大，所以一个网站一个网站的处理
  public function productlist($dshopid){
  //第一步先获取授权信息，
    $sql="select * from `d_shop` where `id`='{$dshopid}';";
    $arr_row = $this->db1->query($sql)->result_array();
    //判断是否存在授权码
    if(!empty($arr_row)){
      foreach ($arr_row as $value) {
        if(empty($value['amazonkey'])){
          continue;
        }
        $amazonkey=json_decode($value['amazonkey'],true);
        //判断术后存在shopid
          if(isset($amazonkey['shopeetoken'])){
            //存在shopid执行下载数据
            return $this->getallproduct($amazonkey['shopeetoken'],$dshopid);
          }
      }
    }
  }

//获取当前店铺产品信息
  public function getallproduct($shopid,$dshopid){
    $itemjs = $this->shopeeapi('itemslist',$shopid);
    $item = json_decode($itemjs,true);
    $items =$item['items'];
    //根据店铺id获取店铺名称
    $shopdata = $this->getshopdata($dshopid);
    //循环获取单个产品信息，然后导入数据库中。
    foreach ($items as $value) {
      return $this->oneproduct($shopid,$dshopid,$value['item_id'],$shopdata);
    }
  }

//获取单个产品信息存入数据库中
/*
  public function oneproduct($shopid,$dshopid,$item_id,$shopdata){

    $productjs = $this->shopeeapi('itemdetail',$shopid,array('item_id'=>$item_id));
    $productls = json_decode($productjs,true);
    //循环获取变体
    $variations = $productls['item']['variations'];
    $currency = $productls['item']['currency'];
    $productname = $productls['item']['name'];
    $productname = str_replace(' ','-', $productname);
    //产品销售链接 构建规则  域名+产品名称（空格用-代替）后面跟-i.店铺id.itemsid
    //域名预先定义好。默认为台湾
      $weburl='https://shopee.tw/';
      if($dshopid == '273') $weburl = 'https://shopee.com.my/';
      if($dshopid == '271') $weburl = 'https://shopee.sg/';
      $producturl= $weburl.$productname.'-i.'.$shopid.$item_id;
    //根据货币单位查询汇率信息
    $currencyls = $this->getcurrency($currency);
      //判断产品状态
      $status = $productls['item']['status'];
      //默认都是正常产品
      $sts = 0;
      if($status == 'DELETED') $sts = 1;
      if($status == 'BANNED') $sts = 3;
    //判断是有变体，如果没有变变体则直接导入本身
    if(count($variations) > 0){
    foreach ($variations as $value) {
      $postdata='';
      //判断状态
      $postdata['types'] = $sts;
      $postdata['platform_id'] = 22;
      $postdata['shopid'] = $dshopid;
      $postdata['shopname'] = $shopdata['name'];
      //根据sku查找产品信息
      $sku = $value['variation_sku'];
      $skuarr = $this->skugoods($sku);
      $postdata['goods_id'] = $skuarr['goods_id'];
      $postdata['parent_sku'] = $skuarr['parent_sku'];
      $postdata['goods_sku'] = $skuarr['goods_sku'];
      $postdata['goods_name'] = $value['name'];
      $postdata['sales_sku'] = $sku;
      $postdata['moneytype'] = $currency;
      $postdata['moneyrate'] = $currencyls['rate'];
      $postdata['original_price'] = $value['price'];
      $postdata['price'] = $value['price'] * $currencyls['rate'];
      $postdata['qty'] = $value['stock'];
      $postdata['sales_time'] = strtotime('m/d/Y H:i:s',$value['create_time']);
      //这个product id 备注写着平台id，所以存入了shopee平台的variation_id 为Shopee对项目变体的唯一标识符。
      $postdata['product_id'] = $value['variation_id'];

      $postdata['product_link'] = urlencode($producturl);
      $this->db1->insert("db_platform_productlist",$postdata);
    }
  }else{
    //没有变体直接导入本体
    $postdata='';
    $postdata['types'] = $sts;
    $postdata['platform_id'] = 22;
    $postdata['shopid'] = $dshopid;
    $postdata['shopname'] = $shopdata['name'];
    $sku = $productls['item']['item_sku'];
    $skuarr = $this->skugoods($sku);
    $postdata['goods_id'] = $skuarr['goods_id'];
    $postdata['parent_sku'] = $skuarr['parent_sku'];
    $postdata['goods_sku'] = $skuarr['goods_sku'];
    $postdata['goods_name'] = $productls['item']['name'];
    $postdata['sales_sku'] = $sku;
    $postdata['moneytype'] = $currency;
    $postdata['moneyrate'] = $currencyls['rate'];
    $postdata['original_price'] = $productls['item']['price'];
    $postdata['price'] = $productls['item']['price'] * $currencyls['rate'];
    $postdata['sales_time'] = strtotime('m/d/Y H:i:s',$productls['item']['create_time']);
    $postdata['product_id'] = $item_id;
    $postdata['product_link'] = urlencode($producturl);
    $this->db1->insert("db_platform_productlist",$postdata);
  }
  return 'test-ok';
   
  }
  */

  //根据货币单位获取汇率等信息
  public function getcurrency($currency){
    $sql="select * from `d_moneyrate` where `name` = '{$currency}';";
    $data = $this->db1->query($sql)->row_array();
    //如果没有该货币这汇率默认为1；
    if(empty($data)){
      $currencyls = array('rate'=>1);
    }else{
      $currencyls = array('rate'=>$data[0]['rate']);
    }
    return $currencyls;
  }

  //根据店铺id获取店铺信息
  public function getshopdata($dshopid){
    $sql = "select * from `d_shop` where `id`='{$dshopid}';";
    $data = $this->db1->query($sql)->row_array();
    $shopdata = array('name'=>$data[0]['name']);
    return $shopdata;
  }

  //根据产品sku，产品goods表查找信息
  public function skugoods($sku){
     $sql="select * from `db_goods` where `goods_sku` = '{$sku}';";
     $date=$this->db1->query($sql)->row_array();
     //判断是否为空如果为空则返回原sku
     if(empty($date)){
       $date2 =$this->db1->get_where("db_goods","cognatelist like '%,{$sku},%'")->result_array();
       if(empty($date2)){
        $skuarr=array('goods_id'=>0,'goods_sku'=>$sku,'goods_parent_sku'=>'');
         return $skuarr;
       }
       $skuarr=array('goods_id'=>$date2[0]['goods_id'],'goods_sku'=>$date2[0]['goods_sku'],'goods_parent_sku'=>$date2[0]['goods_parent_sku']);
        return $skuarr;
     }
      $skuarr=array('goods_id'=>$date[0]['goods_id'],'goods_sku'=>$date[0]['goods_sku'],'goods_parent_sku'=>$date[0]['goods_parent_sku']);
     return $skuarr;
  }


    //检索规定时间内的订单
   public function orderlist($shopid,$dshopid){
    //执行返回物流单号
    $this->returntn($shopid,$dshopid);
     //shopid由start函数传入
   	var_export($shopid);
    $datajson=$this->shopeeapi('orderlist',$shopid);
    var_export($datajson);
    //转码为数组
    $dataarr=json_decode($datajson,true);
    //循环数组，获取订单信息
    foreach ($dataarr['orders'] as $key => $value) {
      $ordersn=$value['ordersn'];
     
      //过滤掉unpaid的订单
      if($value['order_status']=='UNPAID') continue;
      //过滤掉INVALID的订单
      if($value['order_status']=='INVALID') continue;
       //判断订单是否存在，存在的话直接过滤
      $is = $this->isinorder($ordersn,$dshopid);
      if($is == 1 ) continue;
      
      
      //不过滤订单全部抓取
      $this->oneorder($ordersn,$shopid,$dshopid);
    }
   }


   //判断订单是否存在于db_order_list表中 如果存在则跳过执行下一个订单。
   public function isinorder($ordersn,$dshopid){
     $sqql="select * from db_order_list where `tradeid` = '{$ordersn}' and `shopid` = '{$dshopid}';";
     $date=$this->db1->query($sqql)->row_array();
     //判断是否有值，如果没有的话返回0，有的话返回1；
     if ($date["order_id"]) {
       return 1;
     }
     return 0;
   }
   
   //查询单个订单数据，并把该订单导入系统
   public function oneorder($ordersn,$shopid,$dshopid){
   $data=$this->shopeeapi('oneorder',$shopid,array('ordersn'=>$ordersn));
   $data=json_decode($data,true);
   var_export($data);
   if(isset($data['orders'][0])){
    $date=$data['orders'][0];
  }elseif(isset($data['orders'])){
    $date=$data['orders'];
  }else{
    //说明请求数据失败
   return 0; 
  }
              //获取信息准备导入。
 
    foreach ($date['items'] as $value) {
      //判断variation_sku是否为空
      $sku=addslashes(trim(empty($value['variation_sku'])?$value['item_sku']:$value['variation_sku']));
      //判断查询是不是在sku表中，如果有不在的直接中断查询直接状态改为待审查
      $check=$this->db1->get_where("db_goods","goods_sku='{$sku}'")->result_array();
      if (empty($check)) {
          $checklist=$this->db1->get_where("db_goods","cognatelist like '%,{$sku},%'")->result_array();
          if(empty($checklist)){
            $Status=7;
            break;
          }else{
            $Status=2;
          }
      }else{
         $Status=2;
      }
    }


  
      $postdata="";
      $postdata["order_sn"] = $this->amazondata->getNo();
      //测试
      // $postdata["order_sn"]=rand(0,10000);
      $postdata["dates"] = date("Y-m-d");
      $postdata["order_status"] = $Status;
      $postdata["order_source"] ='正常订单';
      $postdata['shipping_status']=0;
      //获取不到用户昵称，使用用户收件人姓名
      $postdata["customerid"] =addslashes(trim($date['recipient_address']['name']));
      //收件人信息
      $postdata["consignee"] =addslashes(trim($date['recipient_address']['name']));
      if($date['recipient_address']['country']!='TW' && $date['recipient_address']['country']!=''){
            $postdata["country"] = ucfirst(strtolower(addslashes(trim($date['recipient_address']['country']))));
            $postdata["country_code"]= addslashes(trim($date['recipient_address']['country']));
            if($date['recipient_address']['country']){
              $rscountry = $this->db1->get_where("d_country","countrynamecn='".$date['recipient_address']['country']."'or countryid = '".$date['recipient_address']['country']."' or countrynamede ='".$date['recipient_address']['country']."'")->result_array();
              if(isset($rscountry[0]["id"])){
                $postdata["country_cn"] = $rscountry[0]["countrynameen"];
                $postdata["country"] = ucfirst(strtolower($rscountry[0]['countrynamecn']));
              }else{
                $postdata["country_cn"] ='';
              }
            }
            $postdata["province"] = $date['recipient_address']['state'];
            $postdata["city"] = $date['recipient_address']['city'];
      }else{
        $postdata["country"] = 'China';
        $postdata["country_code"]= 'CN';
        $postdata["country_cn"]='中国';
        if($date['recipient_address']['country']){
              $rscountry = $this->db1->get_where("d_country","countrynamecn='".$date['recipient_address']['country']."'or countryid = '".$date['recipient_address']['country']."' or countrynamede ='".$date['recipient_address']['country']."'")->result_array();
              if(isset($rscountry[0]["id"])){
                $postdata["province"] = $rscountry[0]["countrynameen"];
              }else{
                $postdata["province"] ='';
              }
            }
        $postdata["city"] = $date['recipient_address']['state'];
      }

      $postdata["address"] = $date['recipient_address']['full_address'];
      $postdata["zipcode"] = $date['recipient_address']['zipcode'];
      $postdata["tel"] = $date['recipient_address']['phone'];
      

      $postdata["tradeid"] = $ordersn;
      //获取店铺信息
      $rshop = $this->db1->get_where("d_shop","id=".$dshopid)->result_array();
      $postdata["shopname"] = $rshop[0]["name"];
      $postdata["shopoper"] = $rshop[0]["updateoper"];
      $postdata["shopid"] = $dshopid;
      //订单金额信息
      $postdata["moneytype"] = $date['currency'];
      $exchange=$this->db1->get_where("d_moneyrate","name='{$date['currency']}'")->result_array();
      $exchangerate = $exchange[0]["rate"];
      //接口计算方式更改，total_amount包含运费
      $postdata["goods_originask"] = $date['total_amount']-$date['estimated_shipping_fee'];
      $postdata["goods_amount"] = $postdata["goods_originask"] * $exchangerate;

      if($date['recipient_address']['country']=='TW' || $date['recipient_address']['country'] == ''){
        $postdata["shipping_originask"] = 55;
        $postdata['shipping_fee'] = 55 * $exchangerate;
      }else{
      //计算出平台补贴费，然后加入到运费里面
        $productfee='';
       foreach ($date['items'] as $value) {
         $productfee += $value['variation_discounted_price'];
       }
      //计算公式，订单实际收入+平台费-商品折后价总和，计算为运费
        $shippingo=$date['escrow_amount']+$date['total_amount']*0.03-$productfee;
        $shippingo=number_format($shippingo,2);
      $postdata["shipping_originask"] = $shippingo;
      $postdata["shipping_fee"] = $shippingo * $exchangerate;
      }
      $postdata["add_time"] = time();
      $postdata["ordertime"] = date("Y-m-d H:i:s",$date['create_time']);
      $postdata["saleschannel"] = 'shopee';
      $postdata["pay_fee"] = $date['total_amount'] * 0.005 * $exchangerate;
      $postdata["platform_fee"] = $date['total_amount'] * 0.03 * $exchangerate;
      $postdata["platform_message"]= $date['message_to_seller'];
      $postdata['moneyrate']  = $exchangerate;
      $postdata['platformID']=$rshop[0]['platfrom'];
      $this->db1->trans_begin();
      try{
				$this->db1->insert("db_order_list",$postdata);

				$orderID = $this->db1->insert_id();

				$factorycode =$this->amazondata->factorycode();
				$weight = 0;
				//循环出来产品sku和产品qty
				$skuarr=array();
				$buyer_product_qty=array();
        $pprice=array();
				foreach ($date['items'] as $value) {
					$skuarr[] = addslashes(trim(empty($value['variation_sku'])?$value['item_sku']:$value['variation_sku']));
					$buyer_product_qty[] = $value['variation_quantity_purchased'];
          $pprice[]=$value['variation_discounted_price'];
				}
				$skui=0;
				$skunum=count($skuarr);
					foreach ($skuarr as $key =>$sku) {
						$sku=trim($sku);
					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$sku."'")->result_array();
					
					if(isset($rgoods[0]["goods_id"]))
					{
						$goods_id = $rgoods[0]["goods_id"];
						$g_weights = $rgoods[0]["g_weight"]?$rgoods[0]["g_weight"]:400;
						$sweight = $buyer_product_qty[$skui]* $g_weights;
						$weight = $weight+$sweight;
						$costprice = 0;
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						if(is_numeric($sku) && preg_match('|^\d{8}$|',$sku))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($sku,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
						}
						



					}else{
						$goods_id = 0 ;
						$costprice = 0;
						$sweight=400;
					}
					$postsell = "";
					$postsell["order_id"] = $orderID;
					$postsell["goods_id"] = $goods_id;
					$postsell["goods_name"] = addslashes($rgoods[0]['goods_name']);
					$postsell["goods_sn"] =  $sku;
					$postsell["costprice"] =$costprice;
					$postsell["goods_number"] = $buyer_product_qty[$skui];
					$postsell["goods_price"] = $pprice[$skui]*$exchangerate;
					$postsell["goods_weight"]=$sweight;
					$postsell["goods_amount"] = $pprice[$skui]* $buyer_product_qty[$skui]*$exchangerate;
					$postsell["originsellprice"] = $pprice[$skui]?$pprice[$skui]:0;
					$postsell["originsku"] = $sku;
					$postsell["product_link"]='';
					//$postsell["sale_remark"]='';
					$this->db1->insert("db_order_sell",$postsell);

					if($goods_id==0)
					{
						$this->db1->update("db_order_list",array("order_status"=>7),"order_id=".$orderID);
					}
					if($weight)
					{
						$this->db1->update("db_order_list",array("orderweight"=>$weight),"order_id=".$orderID);
					}
					$skui++;
				 }
                //更新日志
				$imgdata["goods_id"] = $orderID;	//订单ID
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'shopee接口自动新增订单,交易ID='.$date['ordersn'];
				$imgdata["createUser"] ='auto';
				$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
				

				$this->db1->trans_commit();
			}catch (Exception $e){
				$this->db1->trans_rollback();
				$msg =  $e->getMessage();
				print_r($msg);exit;
			}


   }
   
   //返回运单号
   public function returntn($shopid,$dshopid){
    //根据店铺id来查找未回传运单号的订单
    $listrow= $this->db1->get_where("db_order_list","shopid='{$dshopid}' and is_update_platform='0' and (order_status='4' or order_status = '5' )")->result_array();
    foreach ($listrow as $v) {
      //运单号为空的话，直接跳过 
      if($v['shipping_number']==null) continue;
      $order_id=$v['order_id'];
      $shipping_id=$v['shipping_id'];
      //在shopee上面实际的订单编号
      $ordersn=$v['tradeid'];
      $shippingrow=$this->db1->get_where("db_order_express","id='{$shipping_id}'")->result_array();
      foreach ($shippingrow as $sv) {
        $shipping_name=$sv['wish_express'];
      }
      $shipping_number=$v['shipping_number'];

      $res=$this->shopeeapi('SetTrackingNo',$shopid,array('ordersn'=>$ordersn,'tracking_number'=>$shipping_number));
      var_export($ordersn);
      var_export($shipping_number);
      var_export($res);
      $resarr=json_decode($res,true);
        if($resarr['result']['success_count']=='1'){
          $sql="update `db_order_list` set `is_update_platform` = '1' where `shopid`='{$dshopid}' and `tradeid` = '{$ordersn}';";
          $date=$this->db1->query($sql);
      
        }
      
    }


   }

   //获取退款
   public function returnlist($shopid,$dshopid){
   $list=$this->shopeeapi('returnlist',$shopid);
   $listarr=json_decode($list,true);
   //return $listarr;
   //转为数组，然后把这个内容存入数据库中
   if(isset($listarr['returns'][0])){
   	//存在退款
   	foreach ($listarr['returns'] as $value) {
   		unset($data);
   		$data=array();
   		//这个地方指的是订单原始的编号
   		$ordersn=$value['ordersn'];
   		//首先判断当前退款在数据库中是否存在，如果存在的话，则不需要重复录入
   		$checksql="select * from `db_shopee_refund` where `dsr_ordersn` = '{$ordersn}';";
   		$ckl=$this->db1->query($checksql)->result_array();
   		if(isset($ckl[0]['dsr_id'])) continue;
   		$sql="select * from `db_order_list` where `tradeid`='{$ordersn}';";
   		$li=$this->db1->query($sql)->result_array();
   		$order_id=$li[0]['order_id'];
   		$shopname=$li[0]['shopname'];
   		$shopoper=$li[0]['shopoper'];
   		$order_time=$li[0]['ordertime'];
   		$order_sn=$li[0]['order_sn'];
   	    $data['dsr_ordersn']=$ordersn;
   	    //这个是指的订单编号，fuman平台使用
   	    $data['order_sn']=$order_sn;
   	    $data['order_id']=$order_id;
   	    //店铺信息
   	    $data['shop_id'] = $dshopid;
   	    $data['shopname'] = $shopname;
   	    $data['shopoper'] = $shopoper;
   	    $refund_amount=$value['refund_amount'];
   	    $data['refund_amount']=$refund_amount;
   	    $currency=$value['currency'];
   	    $data['currency']=$currency;
   	    $exchange=$this->db1->get_where("d_moneyrate","name='{$currency}'")->result_array();
        $exchangerate = $exchange[0]["rate"];
   	    $data['moneyrate'] = $exchangerate;
   	    $data['text_reason'] = $value['text_reason'];
   	    $data['refund_amount_rmb'] = $refund_amount*$exchangerate;
   	    //这里的创建时间指的实际就是创建退款的时间，也就是退款时间
   	    $data['refund_time'] = date('Y-m-d H:i:s', $value['create_time']);
   	    //订单时间
   	    $data['order_time'] = $order_time;
   	    $data['returnsn'] = $value['returnsn'];
   	    $this->db1->insert("db_shopee_refund",$data);

   	}
   	 //return $data;
   }

   }
 



   //shopeeapi访问函数
   public function shopeeapi($type,$shopid,$data=array()){
    //当前时间戳
    $timestamp=time();
    //固定值，从客户经理那边获得，为shopee合作所提供
    $partner_id=12127;
    //同上，从客户经理那边所得
    $key='8f4819490abe1caa67bb2207b19a8aebe67548e93339815e7775c15c78e6e462';
    //根据类型来选择部分条件
    if ($type == 'orderlist') {
    //通过订单创建时间来检索订单，查询三天内创建的订单
    $create_time_from=$timestamp-5*24*3600;
    $create_time_to=$timestamp;
     //api查询链接
    $url="https://partner.shopeemobile.com/api/v1/orders/basics";
    $body=array('create_time_from'=>$create_time_from,'create_time_to'=>$create_time_to,'shopid'=>intval($shopid), 'partner_id'=>intval($partner_id), 'timestamp'=>$timestamp);
    }
     //设置运单号    
    if($type == 'SetTrackingNo'){
      $url="https://partner.shopeemobile.com/api/v1/logistics/tracking_number/set_mass";
      $body=array('info_list'=>array(array('ordersn'=>$data['ordersn'],'tracking_number'=>$data['tracking_number'])),'shopid'=>intval($shopid),'partner_id'=>intval($partner_id), 'timestamp'=>$timestamp);

    }

    //获取退款
    if($type == 'returnlist'){
          $create_time_from=$timestamp-14*24*3600;
          $create_time_to=$timestamp;
      $url="https://partner.shopeemobile.com/api/v1/returns/get";
      $body=array('pagination_offset'=>0,'pagination_entries_per_page'=>100,'create_time_from'=>$create_time_from,'create_time_to'=>$create_time_to,'shopid'=>intval($shopid), 'partner_id'=>intval($partner_id), 'timestamp'=>$timestamp);
    }

    if ($type == 'oneorder') {
      $url="https://partner.shopeemobile.com/api/v1/orders/detail";
      // $orderarr=array();
      // $orderarr[]=$ordersn;
      $body=array('ordersn_list'=>array($data['ordersn']),'shopid'=>intval($shopid), 'partner_id'=>intval($partner_id), 'timestamp'=>$timestamp);
    }
    
    //获取商品列表
    if($type == 'itemslist'){
     $url="https://partner.shopeemobile.com/api/v1/items/get";
     $body=array('pagination_offset'=>0,'pagination_entries_per_page'=>100,'shopid'=>intval($shopid), 'partner_id'=>intval($partner_id), 'timestamp'=>$timestamp);
    }

    //获取单个商品详细信息
    if($type == 'itemdetail'){
      $url="https://partner.shopeemobile.com/api/v1/item/get";
      $body=array('item_id' => $data['item_id'],'shopid'=>intval($shopid), 'partner_id'=>intval($partner_id), 'timestamp'=>$timestamp);
    }

    $bodyjson=json_encode($body);
    //拼接基础验证码
    $had=$url.'|'.$bodyjson;
    //获取哈希加密 16进制验证码
    $has=bin2hex(hash_hmac('sha256',$had,'8f4819490abe1caa67bb2207b19a8aebe67548e93339815e7775c15c78e6e462',true));
    //拼接请求头部
    $header=array('Content-Type: application/json',"Authorization:$has");
    //构建curl请求
    $c=curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c,CURLOPT_HTTPHEADER,$header);
    curl_setopt($c,CURLOPT_POST,1);
    curl_setopt($c,CURLOPT_POSTFIELDS,$bodyjson);
    curl_setopt($c,CURLOPT_RETURNTRANSFER,1);
    //获取到数据 json格式
    $datajson=curl_exec($c);
    return $datajson;
   }




}